package Meter::DBI;

#===============================================================================
#     REVISION:  $Id: DBI.pm 124 2011-07-25 10:43:02Z xdr.box@gmail.com $
#  DESCRIPTION:  Database abstraction layer: base class
#===============================================================================

use strict;
use warnings;

use base qw(Class::DBI::SQLite);

use Readonly;
Readonly our $VERSION => qw($Revision: 124 $) [1];

use English qw( -no_match_vars );
use Carp;

#use Smart::Comments;

Readonly my $DBI_OPTIONS => { RaiseError => 1 };
Readonly my $DEFAULT_DB => "$ENV{'METER_ROOT'}/db/meter.db";

use Meter::Utils qw(
    dump_var
);
use Meter::LogParams;
use Meter::Log;

use Meter::Sessions;
use Meter::Meterings;
use Meter::Appartments;
use Meter::Users;
use Meter::Houses;

sub init_db : Log( params_as_hash => 0, result => 0 ) {
    my $class = shift;
    my $db_name = shift || $ENV{'METER_DB'} || $DEFAULT_DB;

    __PACKAGE__->set_db( 'Main', "dbi:SQLite:dbname=$db_name", $DBI_OPTIONS );

    Meter::Sessions->init_table();
    Meter::Meterings->init_table();
    Meter::Appartments->init_table();
    Meter::Users->init_table();
    Meter::Houses->init_table();

    return;
}

sub _croak {    ## no critic (ProhibitUnusedPrivateSubroutines)
    my ( $self, $message, %info ) = @_;

    my $error_message = $message;

    if ( keys %info ) {
        $error_message .= q{; } . dump_var( {%info}, 'INFO' );
    }

    my $logger = get_logger();
    $logger->error($error_message);

    croak $message;
}

sub accessor_name_for {
    my ( $class, $column ) = @_;

    $column =~ s/_id\z//xms;

    return $column;
}

1;
